package com.dragon.framework.config;

import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

/**
 * OkHttp配置
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/17 18:15
 */
public class OkHttpConfig {

    @Value("${okHttp.connect-timeout:30}")
    private Integer connectTimeout;

    @Value("${okHttp.read-timeout:30}")
    private Integer readTimeout;

    @Value("${okHttp.write-timeout:30}")
    private Integer writeTimeout;

    @Value("${okHttp.max-idle-connections:300}")
    private Integer maxIdleConnections;

    @Value("${okHttp.keep-alive-duration:300}")
    private Long keepAliveDuration;

    Logger log = LoggerFactory.getLogger(OkHttpConfig.class);

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient.Builder()
            .sslSocketFactory(sslSocketFactory(), x509TrustManager())
            // 是否开启缓存
            .retryOnConnectionFailure(false)
            .connectionPool(connectionPool())
            .connectTimeout(connectTimeout, TimeUnit.SECONDS)
            .readTimeout(readTimeout, TimeUnit.SECONDS)
            .writeTimeout(writeTimeout, TimeUnit.SECONDS)
            .hostnameVerifier(((hostname, session) -> true))
            // 设置代理
            //.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 8888)))
            // 拦截器
            .addInterceptor(interceptor())
            .build();
    }

    /**
     * X509证书信任管理器类
     *
     * @return X509TrustManager
     */
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    /**
     * SSLSocket工厂
     *
     * @return SSLSocketFactory
     */
    public SSLSocketFactory sslSocketFactory() {
        try {
            // 信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());

            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error("OkHttpConfig SSLSocketFactory异常 {}", e.getMessage(), e);
        }

        return null;
    }

    /**
     * 连接池
     *
     * @return ConnectionPool
     */
    public ConnectionPool connectionPool() {
        return new ConnectionPool(maxIdleConnections, keepAliveDuration, TimeUnit.SECONDS);
    }

    /**
     * 拦截器
     *
     * @return Interceptor
     */
    public Interceptor interceptor() {
        return new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest = request.newBuilder()
                    // .addHeader("accessKeyId", "accessKeyId")
                    // .addHeader("accessKeySecret", "accessKeySecret")
                    .build();
                return chain.proceed(newRequest);
            }
        };
    }

}
